package com.redoor.app.stake.basicdata.mq.sendService.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendCallback;
import com.aliyun.openservices.ons.api.SendResult;
import com.redoor.app.stake.basicdata.commons.BasicDataStatus;
import com.redoor.app.stake.basicdata.model.BaseMqOperationLog;
import com.redoor.app.stake.basicdata.model.BussinessTypeEnum;
import com.redoor.app.stake.basicdata.model.LogEnum;
import com.redoor.app.stake.basicdata.mq.sendService.AbsSendMQService;
import com.redoor.app.stake.basicdata.mq.sendService.SendMQService;
import com.redoor.app.stake.basicdata.service.BasePropService;
import com.redoor.app.stake.basicdata.service.LogService;
import com.redoor.app.stake.common.utils.UUIDTool;
import com.redoornetwork.framework.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 *
 *
 * Created by leoliu on 2017/6/8.
 */
@Service
public class SendMQServiceImpl extends AbsSendMQService implements SendMQService {

    private static final Logger logger = LoggerFactory.getLogger(SendMQServiceImpl.class) ;

    @Autowired
    private LogService logService;

    @Autowired
    private BasePropService basePropService;
    /**
     * 发送 MQ 消息
     *
     * @param topic
     * @param tag
     * @param message
     */
    @Override
    public SendResult sendMessage(String topic, String tag, String message,BussinessTypeEnum.MQ_BUSINESS_TYPE type){
        SendResult sr = null ;
        logger.info("start send mq message");
        BaseMqOperationLog mqOperationLog = new BaseMqOperationLog();
        mqOperationLog.setType(type.getType());
        mqOperationLog.setUuid(UUIDTool.getUUID());
        mqOperationLog.setMessagetype(1);
        mqOperationLog.setStartat(String.valueOf(System.currentTimeMillis()));
        try{
            if(StringUtils.isEmpty(message)){
                throw new ServiceException(BasicDataStatus.PARAM_IS_EMPTY);
            }

            Message mess = new Message(topic, tag, message, message.getBytes());

            mqOperationLog.setMessagetag(mess.getTag());
            mqOperationLog.setMessagebody(new String(mess.getBody()));
            mqOperationLog.setMessagekey(mess.getKey());
            mqOperationLog.setMessageid(mess.getMsgID());
            mqOperationLog.setMessagetopic(mess.getTopic());

            if (!basePropService.initMQFlag()) {
                throw new ServiceException(BasicDataStatus.MQ_FUNCTION_DISABLE);
            }
            sr = producer.send(mess) ;
            logger.info("send result=" + sr.toString()); ;
            logger.info("send result json=" + JSON.toJSONString(sr)); ;
            mqOperationLog.setEndat(String.valueOf(System.currentTimeMillis()));
            mqOperationLog.setStatus(1);
            mqOperationLog.setRemark(JSON.toJSONString(sr));

        } catch(Exception e){
            mqOperationLog.setEndat(String.valueOf(System.currentTimeMillis()));
            mqOperationLog.setStatus(2);
            mqOperationLog.setRemark(e.getLocalizedMessage());

            logger.error("send message error",e);
        }
        logger.info("end send mq message");
        logService.addLogToRedis(mqOperationLog, LogEnum.MQ_LOG);
        return sr ;
    }

    @Override
    public SendResult sendMessage(String topic, String tag, String key, String message,BussinessTypeEnum.MQ_BUSINESS_TYPE type) {
        SendResult sr = null ;
        logger.info("start send mq message");

        BaseMqOperationLog mqOperationLog = new BaseMqOperationLog();
        mqOperationLog.setType(type.getType());
        mqOperationLog.setUuid(UUIDTool.getUUID());
        mqOperationLog.setStartat(String.valueOf(System.currentTimeMillis()));
        mqOperationLog.setMessagetype(1);
        try{
            if(StringUtils.isEmpty(message)){
                throw new ServiceException(BasicDataStatus.PARAM_IS_EMPTY);
            }
            Message mess = new Message(topic, tag,key, message.getBytes()) ;

            mqOperationLog.setMessagetag(mess.getTag());
            mqOperationLog.setMessagebody(new String(mess.getBody()));
            mqOperationLog.setMessagekey(mess.getKey());
            mqOperationLog.setMessageid(mess.getMsgID());
            mqOperationLog.setMessagetopic(mess.getTopic());

            if (!basePropService.initMQFlag()) {
                throw new ServiceException(BasicDataStatus.MQ_FUNCTION_DISABLE);
            }
            sr = producer.send(mess) ;
            logger.info("send result=" + sr.toString()); ;
            logger.info("send result json=" + JSON.toJSONString(sr)); ;

        }catch(Exception e){
            mqOperationLog.setEndat(String.valueOf(System.currentTimeMillis()));
            mqOperationLog.setStatus(2);
            mqOperationLog.setRemark(e.getLocalizedMessage());

            logger.error("send message error",e);
        }
        logger.info("end send mq message");
        logService.addLogToRedis(mqOperationLog, LogEnum.MQ_LOG);
        return sr ;
    }

    public void sendAsync(String topic, String tag, String message,BussinessTypeEnum.MQ_BUSINESS_TYPE type,SendCallback sendCallback){
        logger.info("start send sendAsync mq message");
        BaseMqOperationLog mqOperationLog = new BaseMqOperationLog();
        mqOperationLog.setUuid(UUIDTool.getUUID());
        mqOperationLog.setType(type.getType());
        mqOperationLog.setMessagetype(1);
        mqOperationLog.setStartat(String.valueOf(System.currentTimeMillis()));
        try{
            if(StringUtils.isEmpty(message)){
                throw new ServiceException(BasicDataStatus.PARAM_IS_EMPTY);
            }
            Message mess = new Message(topic, tag, message.getBytes()) ;
            mqOperationLog.setMessagetag(mess.getTag());
            mqOperationLog.setMessagebody(new String(mess.getBody()));
            mqOperationLog.setMessagekey(mess.getKey());
            mqOperationLog.setMessageid(mess.getMsgID());
            mqOperationLog.setMessagetopic(mess.getTopic());

            if (!basePropService.initMQFlag()) {
                throw new ServiceException(BasicDataStatus.MQ_FUNCTION_DISABLE);
            }
            producer.sendAsync(mess,sendCallback);

            mqOperationLog.setEndat(String.valueOf(System.currentTimeMillis()));
            mqOperationLog.setStatus(1);
            mqOperationLog.setRemark("sendAsync");
        }catch(Exception e){
            mqOperationLog.setEndat(String.valueOf(System.currentTimeMillis()));
            mqOperationLog.setStatus(2);
            mqOperationLog.setRemark(e.getLocalizedMessage());

            logger.error("send message error",e);
        }
        logService.addLogToRedis(mqOperationLog, LogEnum.MQ_LOG);
        logger.info("end send sendAsync mq message");
    }

    public void sendOneway(String topic, String tag, String message,BussinessTypeEnum.MQ_BUSINESS_TYPE type){
        logger.info("start send sendOneway mq message");
        BaseMqOperationLog mqOperationLog = new BaseMqOperationLog();
        mqOperationLog.setUuid(UUIDTool.getUUID());
        mqOperationLog.setType(type.getType());
        mqOperationLog.setMessagetype(1);
        mqOperationLog.setStartat(String.valueOf(System.currentTimeMillis()));
        try{
            if(StringUtils.isEmpty(message)){
                throw new ServiceException(BasicDataStatus.PARAM_IS_EMPTY);
            }
            Message mess = new Message(topic, tag, message.getBytes()) ;
            mqOperationLog.setMessagetag(mess.getTag());
            mqOperationLog.setMessagebody(new String(mess.getBody()));
            mqOperationLog.setMessagekey(mess.getKey());
            mqOperationLog.setMessageid(mess.getMsgID());
            mqOperationLog.setMessagetopic(mess.getTopic());

            if (!basePropService.initMQFlag()) {
                throw new ServiceException(BasicDataStatus.MQ_FUNCTION_DISABLE);
            }
            producer.sendOneway(mess);

            mqOperationLog.setEndat(String.valueOf(System.currentTimeMillis()));
            mqOperationLog.setStatus(1);
            mqOperationLog.setRemark("sendOneway");
        }catch(Exception e){
            mqOperationLog.setEndat(String.valueOf(System.currentTimeMillis()));
            mqOperationLog.setStatus(2);
            mqOperationLog.setRemark(e.getLocalizedMessage());

            logger.error("send message error",e);
        }
        logService.addLogToRedis(mqOperationLog, LogEnum.MQ_LOG);
        logger.info("end send sendOneway mq message");
    }

}
